package org.tong.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.tong.bean.Order;

import java.math.BigInteger;
import java.sql.*;
import java.util.List;

@Repository
public class OrderDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Order> queryAll() {
        return jdbcTemplate.query("select * from t_order", getRowMapper());
    }

    public Order queryByOrderId(BigInteger orderId) {
        return (Order) jdbcTemplate.queryForObject("select * from t_order where order_id=?", getRowMapper(), orderId);
    }

    private RowMapper getRowMapper() {
        return new RowMapper<Order>() {
            @Override
            public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
                Order order = new Order();
                order.setOrderId(rs.getBigDecimal(1).toBigInteger());
                order.setOrderNo(rs.getString(2));
                order.setCreateName(rs.getString(3));
                order.setPrice(rs.getBigDecimal(4));
                return order;
            }
        };
    }

    public BigInteger insert(Order order) {
        String sql = "insert into t_order (order_no, create_name, price)values(?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement preparedStatement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                preparedStatement.setString(1, order.getOrderNo());
                preparedStatement.setString(2, order.getCreateName());
                preparedStatement.setBigDecimal(3, order.getPrice());
                return preparedStatement;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        order.setOrderId(new BigInteger(id.toString()));
        return order.getOrderId();
    }
}
